<template>
  <div class="app-container">
    <el-select v-model="queryParams.vesselName" filterable clearable placeholder="Vessel" @change="selectVessel" style="width:180px">
      <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels"> </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" @change="selectVoyage">
      <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages"> </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.pol" filterable clearable placeholder="Port">
      <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods"> </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-button type="primary" icon="search"  @click="search">Search</el-button>
    &nbsp;&nbsp;

    <el-empty v-if="listData.length === 0" description="No Data" :image-size="100" />
    <h3 style="text-align: center" v-if="listData.length > 0"><strong>CARGO MANIFEST</strong></h3>
    <div v-for="(item, index) in listData" :key="index" class="item-box">
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>VESSEL NAME:</strong></span
          >{{ item.vesselName }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>VOYAGE</strong></span
          >{{ item.voyageNo }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>FLAG</strong></span
          >{{ item.flagState }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>IMO No.</strong></span
          >{{ item.imoNumber }}
        </el-col>
      </el-row>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>PORT OF LOADING</strong></span
          >{{ item.pol }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>PORT OF DISCHARGING</strong></span
          >{{ item.pod }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>DATE OF DEPARTURE</strong></span
          >{{ item.atd }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>N.R.T.</strong></span
          >{{ item.nrt }}
        </el-col>
      </el-row>
      <el-row class="manifest-tip-item__wrapper">
        <div :span="2" class="manifest-tip-item" v-for="(val, valIndex) in buttonList" :key="valIndex" style="margin-right: 20px;">
          <el-tooltip class="box-item" effect="dark" :content="'Please upload '+ val.label + ' you’ve choosen accordingly (word/excel)'" placement="bottom">
            <el-button type="primary" v-hasPermi="['blProcess:edit']" @click="onMerge(item, valIndex)">{{ val.label }}</el-button>
          </el-tooltip>
        </div>
        <el-col :span="2" class="manifest-tip-item" style="padding-top: 0">
          <el-button type="primary" @click="handleExport(item)" v-hasPermi="['blProcess:export']">Export</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="padding: 0 16px">
        <el-col :span="4" v-for="(val, valIndex) in item.details" :key="valIndex" style="margin-bottom: 16px">
          <el-card class="box-card" @dblclick="blNoDetail(val)">
            <span class="card-title">{{ val.blNo }}</span>
            <div class="btn-content">
              <div v-for="(btnItem, btnIndex) in buttonList" :key="btnIndex" style="margin-right: 10px;" :class="['btn-item',val[btnItem.fileName]?'fileActive':'']" >{{ btnItem.label }}</div>
            </div>
            <el-checkbox size="large" v-model="val.check" class="check-box" />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog class="edit_dialog" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
      <el-form :model="formParam" ref="custForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="MARKS & NOS." label-width="220px" prop="marks" required>
              <el-input type="textarea" v-model="formParam.marks"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="DESCRIPTION OF GOODS" label-width="220px" prop="goodsDesc" required>
              <el-input type="textarea" v-model="formParam.goodsDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="REMARKS" label-width="220px" prop="remark">
              <el-input type="textarea" v-model="formParam.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button>
          <el-button @click="resetForm" type="warning">{{ $t("ship.button.reset") }}</el-button>
          <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
        </span>
      </template>
    </el-dialog>
    <MergeModal ref="mergeModal" @success="onSuceess" />
    <SplitModal ref="splitModal" @success="onSuceess" />
    <BlDetailModal ref="blDetailModal"/>
    <FileUpload
      ref="fileUploadRef"
      :isDownTemplate="false"
      :uploadData="uploadData"
      :uploadFileUrl="uploadFileUrl"
      :fileType="fileType"
      @update:modelValue="updateFileUpload"
    />
  </div>
</template>
<script lang="ts" setup>
// @ts-nocheck
import { ref, onMounted, reactive, toRef } from "vue";
import { downloadFile } from "@/utils/downloadFile";
import service from "@/utils/request";
import { hasAuth } from "@/utils/auth";
import { useMixinAuth } from "@/components/mixin/auth.js";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import SplitModal from "./modules/SplitModal.vue";
import MergeModal from "./modules/MergeModal.vue";
import BlDetailModal from './modules/BlDetailModal.vue';
import { useTablesDrag } from "@/hooks/useHooks";
const { tableRefs, proxy, initTableDrag } = useTablesDrag();

const auth = useMixinAuth();
onMounted(async () => { 
  let result = await service.get("/shipping/schedule/getAllSchedule");
  if (result) {
    vessels.value = result.data;
  }
});
const buttonList = [
  {
    label: "Split",
    fileName:'splitFileUrl'
  },
  {
    label: "Combine",
    fileName:'combineFileUrl'
  },
  {
    label: "Correction",
    fileName:'correctionFileUrl'
  },
  {
    label: "LOI",
    fileName:'loiFileUrl'
  }
];
const tips = "Please upload LOI you’ve choosen accordingly (word/excel)";
let vessels = ref([] as any);
let voyages = ref([] as any);
let pols = ref([] as any);
let pods = ref([] as any);
const statuss = ["draft", "close"];
const handleExport = item => {
  downloadFile(
    "/shipping/cargoManifest/export/" + item.id,
    queryParams,
    `${item.vesselName}_${item.voyageNo}_${item.pol}_${item.pod}.xlsx`
  );
};
// 请求搜索下来条件
const getVoyageList = async () => {
  const { data } = await service.get("/shipping/voyage/list", {
    params: { status: 0 }
  });
  if (data) {
    voyages.value = data;
  }
};

const total = ref(0);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  voyageId: null,
  status: 0,
  type: 1,
  orderByColumn: undefined,
  isAsc: undefined
});

const listData = ref([]);

// 搜索列表
const refreshTable = async () => {
  let result = await service.get("/shipping/cargoManifest/getBlTable", {
    params: queryParams
  });
  listData.value = result.data;
  listData.value.forEach(item=>{
    item.details.forEach(item=>{
      item.check=false
    })
  })
  total.value = result.total;
  initTableDrag();
};

const custForm = ref(null);
const dialogTitle = ref("");
const initForm = {
  id: null,
  totalWeight: null,
  totalUnits: null,
  totalVolume: null,
  shipper: null,
  consignee: null,
  marks: null,
  goodsDesc: null,
  remark: null
};

const formParam = reactive(Object.assign({}, initForm));
let dialogFormVisible = ref(false);

const editClickEvent = (row: any) => {
  dialogTitle.value = "Update Manifest";
  dialogFormVisible.value = true;
  Object.keys(initForm).forEach(k => (formParam[k] = row[k]));
  isAdd = false;
};

let isAdd = false;
const pageQuery = async e => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = async () => {
  await service["put"]("shipping/cargoManifest", formParam);
  // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  dialogFormVisible = false;
  refreshTable();
};


//按钮操作
const checkList=ref()
const onMerge = (item, index) => {
  uploadData.value.ids=''
  checkList.value=item.details.filter(item => item.check);
  if(checkList.value.length<1){
    ElMessage({
      message: "Select at least one option for operation",
      type: "warning"
    }); 
    return;
  }
  if (checkList.value.length > 1&&index===0) {
    ElMessage({
      message: "Only one split can be selected",
      type: "warning"
    });
    return;
  }
  if (checkList.value[0].blNo.length==16&&index===0) {
    ElMessage({
      message: "The BLNo has been split.",
      type: "warning"
    });
    return;
  }
   if (checkList.value.length < 2&&index===1) {
    ElMessage({
      message: "Please select at least two items",
      type: "warning"
    });
    return;
  }
  checkList.value.forEach(item=>{
    uploadData.value.ids += item.id+','
  });
  uploadData.value.type = index;
  uploadFileForm();
};
const onSuceess = () => {
  checkList.value=[]
  refreshTable();
};

// 拆单操作
const onSplitEvent = (row: any) => {
  proxy.$refs["splitModal"].onInit({ ...row, uploadSuccessUrl });
};

// 合单
const handleMerge = (details) => {
  proxy.$refs["mergeModal"].onInit({ details,uploadSuccessUrl });
};

const handleClose = async row => {
  ElMessageBox.confirm("CONFIRM CLOSED？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel"
  }).then(async () => {
    await service.put(`shipping/cargoManifest/close/`, row);
    ElNotification.success({
      title: "Prompt information",
      message: "close manifest success!",
      position: "bottom-right"
    });
    refreshTable();
  });
};

const selectVessel = async () => {
  queryParams.voyageNo = null;
  queryParams.pol = null;
  queryParams.pod = null;
  voyages.value = [];
  pods.value = [];
  //@ts-ignore
  let item = vessels.value.find(n => n.vesselName == queryParams.vesselName); 
  voyages.value = item.schedules;
};

const selectVoyage = async () => {
  //@ts-ignore
  let item = voyages.value.find(n => n.voyageNo == queryParams.voyageNo);
  pods.value = item.pods;
};

// 上传凭证
const uploadFileUrl = ref("/shipping/cargoManifest/uploadVoucher");
const uploadData = ref({
  ids: '',
  type: 0
});
const fileType = ref([".pdf"]);
const fileUploadRef = ref(null);
const uploadSuccessUrl = ref(null);
const uploadFileForm = () => {
  proxy.$refs["fileUploadRef"].dialogUploadFileForm();
};
const updateFileUpload= (data: any) => { 
  uploadSuccessUrl.value=data
  if(uploadData.value.type==0){
    onSplitEvent(checkList.value[0])
  }
  if(uploadData.value.type==1){
    handleMerge(checkList.value)
  }
};

//查看blno详情
const blNoDetail=(item)=>{
  proxy.$refs["blDetailModal"].onInit(item);
}

</script>
<style lang="scss" scoped>
.manifest-tip-item__wrapper {
  padding-left: 16px;
  &:first-child {
    padding-top: 16px;
  }
  .manifest-tip-item {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 0 2px 16px 0;
    font-size: 13px;
    .title {
      display: inline-block;
      width: 165px;
    }
  }
}
.el-card__body{
  padding: 10px;
}
.box-card {
  position: relative;
  cursor: pointer;
  .check-box {
    position: absolute;
    top: -6px;
    right: 6px;
  }
  
  .btn-item{
    padding: 2px;
    background: rgb(212, 210, 210);

  }
  .fileActive{
    background: rgb(250, 248, 107);
  }
  .btn-content{
    margin-top: 10px;
    display: flex;
    font-size: 14px;
  }
}
</style>
